const {app, BrowserWindow, ipcMain} = require('electron')
const crypto = require('crypto')
const path = require('path')

function createWindow() {
    const win = new BrowserWindow({
        width: 1000,
        height: 800,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            contextIsolation: true,
            nodeIntegration: false
        }
    })
    win.loadFile('index.html')
}

app.whenReady().then(() => {
    createWindow()

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow()
        }
    })
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})

// AES加密处理
ipcMain.handle('encrypt', (_, {plaintext, key}) => {
    try {
        const keyBuffer = Buffer.from(key, 'utf8')
        validateKeyLength(keyBuffer)

        const cipher = crypto.createCipheriv(
            `aes-${keyBuffer.length * 8}-ecb`,
            keyBuffer,
            null
        )
        let encrypted = cipher.update(plaintext, 'utf8', 'hex')
        encrypted += cipher.final('hex')
        return {result: encrypted}
    } catch (error) {
        return {error: error.message}
    }
})

// AES解密处理
ipcMain.handle('decrypt', (_, {ciphertext, key}) => {
    try {
        const keyBuffer = Buffer.from(key, 'utf8')
        validateKeyLength(keyBuffer)

        const decipher = crypto.createDecipheriv(
            `aes-${keyBuffer.length * 8}-ecb`,
            keyBuffer,
            null
        )
        let decrypted = decipher.update(ciphertext, 'hex', 'utf8')
        decrypted += decipher.final('utf8')
        return {result: decrypted}
    } catch (error) {
        return {error: error.message}
    }
})

function validateKeyLength(keyBuffer) {
    if (![16, 24, 32].includes(keyBuffer.length)) {
        throw new Error(`密钥长度必须为16/24/32字节 (当前: ${keyBuffer.length}字节)`)
    }
}
